﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace CFR.Silverlight.Scheduling
{
    public class DayViewColumnPresenter : Panel
    {
        private DayView _parentDayView;
        internal DayView ParentDayView { 
            get { return _parentDayView; }
            set { 
                _parentDayView = value;
                value.Scheduler.StartDateChanged += new EventHandler(Scheduler_StartDateChanged);
                value.Scheduler.EndDateChanged += new EventHandler(Scheduler_EndDateChanged);
            }
        }

        void Scheduler_EndDateChanged(object sender, EventArgs e)
        {
            Refresh();
        }

        void Scheduler_StartDateChanged(object sender, EventArgs e)
        {
            Refresh();
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            double left = 0d;
            double widthEach = finalSize.Width / (double)Children.Count;

            for(int i=0;i < Children.Count;i++)
            {
                DayViewColumn dvi = (DayViewColumn)Children[i];

                dvi.Arrange(new Rect(i * widthEach, 0, widthEach, finalSize.Height));
            }

            return base.ArrangeOverride(finalSize);
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (DayViewColumn dvi in Children)
            {
                dvi.Measure(new Size(availableSize.Width / (double)Children.Count, availableSize.Height));
            }

            return base.MeasureOverride(availableSize);
        }

        public void Refresh()
        {            
            RecreateDayViewItems();
            InvalidateMeasure();
            InvalidateArrange();
        }

        private void RecreateDayViewItems()
        {
            this.Children.Clear();

            foreach (DateTime date in ParentDayView.Dates)
            {
                DayViewColumn item = new DayViewColumn();                
                item.ParentPresenter = this;
                item.Date = date;

                if (date.Date == DateTime.Now.Date)
                    item.Background = new SolidColorBrush(Color.FromArgb(Math.Min(ParentDayView.Scheduler.TodayBackgroundColor.A, (byte)100), ParentDayView.Scheduler.TodayBackgroundColor.R, ParentDayView.Scheduler.TodayBackgroundColor.G, ParentDayView.Scheduler.TodayBackgroundColor.B));

                this.Children.Add(item);
            }

        }
    }
}
